<template>
  <div class="app-container">
    <div v-for="(item,index) in allList">
      <el-alert
        :title="item.title"
        type="success"
        center
        @close="delLabel(index)"
        close-text="删除标签">
      </el-alert>
      <div v-if="index!==allList.length-1">
        <div v-show="allList.length-1>=index">
          <el-divider><svg-icon icon-class="welcome"/></el-divider>
        </div>
      </div>
      <div v-else>
        <el-divider><el-button @click="addLabel" size="mini" type="success" icon="el-icon-plus" circle></el-button></el-divider>
      </div>
    </div>
  </div>
</template>

<script>

  import {getLabelList,addLabel,delLabel} from '@/api/label'

  export default {
  name: 'labelManagement',
  data() {
    return {
      allList: []
    }
  },
  created() {
    this.getList()//初始化数据
  },
  methods: {
    async getList() {
      const { data } = await getLabelList()//同步等待结果,必须是data
      this.allList=data;
    },
    addLabel(){
      this.$prompt('请输入标签名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        addLabel(value).then(res=>{
          this.$message({
            type: 'success',
            message: '添加成功'
          });
          const label=res.data;
          label.index=this.allList.length;
          this.allList.push(label);
          console.log(this.allList)
        })
      }).catch(() => {
        //
      });
    },
    delLabel(index){
      let ed=null;//获取子组件对象
      let mC=this.$children;
      const title=this.allList[index].title;
      for(let i=0;i<mC.length;i++){
        if(mC[i].myT===title)
          ed=mC[i];
      }

      console.log("element源码修改,需手动调用子组件关闭Alert")

      const labelId=this.allList[index].id;
      this.$confirm('确定要删除此标签吗?(标签下有博客会失败)', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delLabel(labelId).then(res=>{
          if(res.msg==='success'){
            ed.visible=false;//调用子组件关闭Alert
            this.$message({
              type: 'success',
              message: '已删除'
            });
            this.allList.splice(index,1);
          }else{
            this.$message({
              type: 'error',
              message: '此标签下有博客,不可删除'
            });
          }
        })
      }).catch(()=>{
        //error
      });
    }
  },
  computed:{
  }
}
</script>

<style lang="scss" scoped>

</style>
